<?php

namespace app\Index\controller;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use think\Controller;
use think\Db;
use think\exception\PDOException;
use think\Request;

class Index extends Controller
{

    private $start_time = 1740035876;
    private $redis;
    public function initialize()
    {
        $this->redis = new \Redis();
        $this->redis->connect("127.0.0.1","6379");
    }

    public function index()
    {
        return view("index");
    }

    //获取服务器时间
    public function getTime()
    {
        if(!session("mobile")){
            return json(['status'=>"fail","msg"=>"请先去登录"]);
        }
        $this->start_time = $this->start_time<time()&&time()-$this->start_time>60?(time()+5):$this->start_time;
        $tt = $this->start_time - time();
        if($tt<0){
            $tt = 'stop';
        }
        return json(['status'=>"success","time"=>$tt]);
    }

    //获取秒杀地址
    public function getSecKillPath(Request $request)
    {
        if(!session("mobile")){
            return json(['status'=>"fail","msg"=>"请先去登录"]);
        }
        //获取网络IP
        $ip = $request->server("REMOTE_ADDR");
        if($this->redis->exists($ip)){
            if($this->redis->get($ip)>3){
                return json(['status'=>"fail","msg"=>"请求次数过多".$this->redis->get($ip)]);
            }else{
                $this->redis->incr($ip);
            }
        }else{
            $this->redis->set($ip,1);
        }
        $id = $request->param('id');
        $url = md5(session("mobile").$id);
        $this->redis->set($url,1);
        return json(['status'=>"success","url"=>$url]);
    }

    //下单接口
    public function order(Request $request)
    {
        if(!session("mobile")){
            return json(['status'=>"fail","msg"=>"请先去登录"]);
        }
        $id = $request->param("id");
        $url = $request->param("url");
        if(!$this->redis->exists($url)){
            return json(['status'=>"fail","msg"=>"请求地址不合法"]);
        }
        if(!$this->redis->get($url)){
            return json(['status'=>"fail","msg"=>"秒杀活动你已经参加过了"]);
        }
        $this->redis->set($url,0);
        $mobile = session("mobile");
        //实际业务处理
        //sql 语句实现的秒杀功能
//        try{
//            Db::startTrans();
//            $res = Db::table('goods')->where('id',$id)->setDec('num');//(update delete 和 insert语句 是悲观锁)
//            $num = Db::table("goods")->where('id',$id)->value('num');//(select 语句 是乐观锁)
//            if($num<0){
//                return json(['status'=>"fail","msg"=>"秒杀失败"]);
//            }
//            $ret = Db::table("orders")->insertGetId(['mobile'=>$mobile,"goods_id"=>$id]);
//            if($res && $ret){
//                Db::commit();
//            }
//        }catch (PDOException $exception){
//            return json(['status'=>"fail","msg"=>$exception->getMessage()]);
//            Db::rollback();
//        }

        $good_id = $this->redis->lpop("goods_id");
        if($good_id){
           $this->sendOrder(json_encode(["mobile"=>$mobile,"good_id"=>$good_id]));
            return json(['status'=>'success','msg'=>'秒杀成功']);
        }else{
           return json(['status'=>"fail","msg"=>"秒杀失败"]);
        }
    }

    //发送
    public function sendOrder($data)
    {
      $connect = new AMQPStreamConnection(config("rabbitmq.server"),config("rabbitmq.port"),config("rabbitmq.user"),config("rabbitmq.password"));
      $channel = $connect->channel();
      $queue_name = config("rabbitmq.rabbit_queue");
      $channel->queue_declare($queue_name,false,false,false,false);
      $msg = new AMQPMessage($data);
      $channel->basic_publish($msg,"",$queue_name);
      $channel->close();
      $connect->close();
    }


    public function addGoods(Request $request)
    {
        $num = $request->param("num");
        for($i=0;$i<$num;$i++)
        {
            $this->redis->rPushx("goods_id",++$i);
        }
    }


}
